/**
 *====================================================
 * 文件名称: EnterpriseActionApiImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月24日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.member.action.v1;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.docx4j.model.datastorage.XPathEnhancerParser.variableReference_return;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baidu.aip.imageclassify.ImageClassifyConsts;
import com.timevale.tgtext.text.pdf.parser.v;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.member.action.v1.dto.EnterpriseCastor;
import com.yuexunit.finance.member.action.v1.model.DaysEarningBaseDetail;
import com.yuexunit.finance.member.action.v1.model.DaysEarningEnterpriseBaseDetail;
import com.yuexunit.finance.member.action.v1.model.EarningSummaryBaseDetail;
import com.yuexunit.finance.member.action.v1.model.MonthEarningDetailInfo;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.LoanNoticeEntity;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.LoanNoticeService;
import com.yuexunit.finance.statement.entity.DaysEarningEntity;
import com.yuexunit.finance.statement.entity.EarningSummaryEntity;
import com.yuexunit.finance.statement.service.DaysEarningService;
import com.yuexunit.finance.statement.service.EarningSummaryService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.StringUtil;


/**
 * @ClassName: EnterpriseActionApiImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月24日 下午10:33:27
 */
@Implements(DaysEarningActionApi.class)
public class DaysEarningActionApiImpl implements DaysEarningActionApi {

	private static final DaysEarningBaseDetail DaysEarningBaseDetail = null;

	public static Logger logger = LoggerFactory.getLogger(DaysEarningActionApiImpl.class);

	private DaysEarningService daysEarningService = ComponentFactory.loadClass(DaysEarningService.class);
	
	private EarningSummaryService earningSummaryService = ComponentFactory.loadClass(EarningSummaryService.class);
	
	private FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
	
	private LoanNoticeService loanNoticeService = ComponentFactory.loadClass(LoanNoticeService.class);
	
	@Override
	public PageList<DaysEarningBaseDetail> inquireDaysEarningPageList(Double interest, String enterpriseName,
			Date interestDates, Date createDateTimeEnd, Long financeId, String financeNumber, Long enterpriseId, PageCriteria page) {
		Integer createDateTimeBegins=null;
		if(interestDates !=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			String interestDates2=sdf.format(interestDates);
			String interestDates3=interestDates2.replace("-", "");
			createDateTimeBegins= Integer.valueOf(interestDates3);
		}
		Integer createDateTimeEnds=null;
		if(createDateTimeEnd !=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			String createDateTimeEnd2=sdf.format(createDateTimeEnd);
			String createDateTimeEnd3=createDateTimeEnd2.replace("-", "");
			createDateTimeEnds= Integer.valueOf(createDateTimeEnd3);
		}
		PageList<DaysEarningEntity> pages = daysEarningService.inquireDaysEarningPageList(interest, enterpriseName, createDateTimeBegins, createDateTimeEnds, financeId, financeNumber, enterpriseId, page);
		PageList<DaysEarningBaseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (DaysEarningEntity entity : pages) {
			results.add(EnterpriseCastor.toDaysEarningBaseDetail(entity));
		}
		return results;
	}
	
	@Override
	public DaysEarningBaseDetail inquireDaysEarningDetail(Long daysEarningId, Date interestDates,Long financeId) {
		Integer interestDate=null;
		if(interestDates !=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			String interestDates2=sdf.format(interestDates);
			String interestDates3=interestDates2.replace("-", "");
			interestDate= Integer.valueOf(interestDates3);
		}
		DaysEarningEntity dee = daysEarningService.inquireDaysEarningDetail(daysEarningId, interestDate, financeId);
		if (dee == null) {
			return DaysEarningBaseDetail;
		}
		DaysEarningBaseDetail debd = EnterpriseCastor.toDaysEarningBaseDetail(dee);
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(dee.getFinanceId());
		if (finance == null) {
			return DaysEarningBaseDetail;
		}
		debd.setFinanceAmount(finance.getFinanceAmount());
		debd.setFinanceDays(finance.getLoanTimeLimit());
		List<LoanNoticeEntity> ls = loanNoticeService.inquireLoanNoticeList(dee.getFinanceId());
		if (ls != null && ls.size() > 0) {
				debd.setFinanceOffDate(DateUtils.addDateField(DateUtils.fromDateInt(ls.get(0).getLoanDate()), Calendar.DATE, finance.getLoanTimeLimit()));
				debd.setFinanceAmountDays(DateUtils.daysBetween(DateUtils.fromDateInt(ls.get(0).getLoanDate()), DateUtils.now()));
			}
			return debd;
		}
	
	@Override
	public PageList<DaysEarningEnterpriseBaseDetail> inquireSaysEarningEnterprisePageList(String enterpriseName, Date interestDts,
			Date createDateTimeEnd,Long financeId, PageCriteria page) {
		StringBuffer countSql=null;
		Integer createDateTimeBegins=null;
		Integer createDateTimeEnds=null;

		if(interestDts !=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			String interestDts2=sdf.format(interestDts);
			String interestDts3=interestDts2.replace("-", "");
			createDateTimeBegins= Integer.valueOf(interestDts3);
		}
		if(createDateTimeEnd !=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
			String createDateTimeEnd2=sdf.format(createDateTimeEnd);
			String createDateTimeEnd3=createDateTimeEnd2.replace("-", "");
			createDateTimeEnds= Integer.valueOf(createDateTimeEnd3);
		}
		if(StringUtil.isNotBlank(enterpriseName) && interestDts!=null && financeId !=null){
			countSql = new StringBuffer("SELECT count(*) c FROM view_fin_days_earning_enterprise v WHERE");
			countSql.append(" v.FINANCE_ID = ").append(financeId);
			countSql.append(" AND v.ENTERPRISE_NAME = ").append("'" + enterpriseName + "'");
			countSql.append(" AND v.INTEREST_DT = ").append(createDateTimeBegins);
		}else{
			countSql = new StringBuffer("SELECT count(*) c FROM view_fin_days_earning_enterprise v WHERE");
			if (financeId !=null) {
				countSql.append(" v.FINANCE_ID = ").append(financeId);
			}
			if(createDateTimeEnd !=null && interestDts !=null && StringUtil.isNotBlank(enterpriseName)){
					countSql.append(" v.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
					countSql.append(" AND v.INTEREST_DT <=  ").append(createDateTimeEnds).append(" AND ").append(" v.INTEREST_DT  >= ").append(createDateTimeBegins);	
				}else if(createDateTimeEnd !=null && interestDts !=null){
					countSql.append(" v.INTEREST_DT <=  ").append(createDateTimeEnds).append(" AND ").append(" v.INTEREST_DT  >= ").append(createDateTimeBegins);
				}else if(StringUtil.isNotBlank(enterpriseName) && interestDts !=null){
					countSql.append(" v.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
					countSql.append(" AND v.INTEREST_DT = ").append(createDateTimeBegins);			
				}else if(StringUtil.isNotBlank(enterpriseName) && createDateTimeEnd !=null){
					countSql.append(" v.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
					countSql.append(" AND v.INTEREST_DT = ").append(createDateTimeEnds);			
				}else{
					countSql.append(" v.INTEREST_DT = ").append(createDateTimeBegins);
			}
		}
		StringBuffer sql=null;
		if(StringUtil.isNotBlank(enterpriseName) && interestDts !=null && financeId !=null){
			sql = new StringBuffer("SELECT ENTERPRISE_ID, FINANCE_ID, ENTERPRISE_NAME, FINANCE_AMOUNT, BULKSTOCK_VALUATION, INTEREST , INTEREST_DT , LOAN_DATE, FINANCE_NUMBER FROM view_fin_days_earning_enterprise v1 WHERE");
			sql.append(" v1.FINANCE_ID = ").append(financeId);
			sql.append(" AND v1.ENTERPRISE_NAME = ").append("'" + enterpriseName + "'");
			sql.append(" AND v1.INTEREST_DT = ").append(createDateTimeBegins);
			sql.append(" ORDER BY ENTERPRISE_NAME  DESC LIMIT " + (page.getPageIndex() - 1) * page.getPageSize() + " , " + page.getPageSize());
		}else{
			sql = new StringBuffer("SELECT ENTERPRISE_ID, FINANCE_ID, ENTERPRISE_NAME, FINANCE_AMOUNT, BULKSTOCK_VALUATION, INTEREST , INTEREST_DT , LOAN_DATE, FINANCE_NUMBER FROM view_fin_days_earning_enterprise v1 WHERE");
			if (financeId !=null) {
				sql.append(" v1.FINANCE_ID = ").append(financeId);
			}
			if(createDateTimeEnd !=null && interestDts !=null && StringUtil.isNotBlank(enterpriseName)){
				sql.append(" v1.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
				sql.append(" AND v1.INTEREST_DT <=  ").append(createDateTimeEnds).append(" AND ").append(" v1.INTEREST_DT  >= ").append(createDateTimeBegins);
			}else if (interestDts !=null && createDateTimeEnd !=null) {
				sql.append(" v1.INTEREST_DT <=  ").append(createDateTimeEnds).append(" AND ").append(" v1.INTEREST_DT  >= ").append(createDateTimeBegins);
			}else if(StringUtil.isNotBlank(enterpriseName) && interestDts !=null){
				sql.append(" v1.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
				sql.append(" AND v1.INTEREST_DT = ").append(createDateTimeBegins);			
			}else if(StringUtil.isNotBlank(enterpriseName) && createDateTimeEnd !=null ){
				sql.append(" v1.ENTERPRISE_NAME").append(" like '%" + enterpriseName + "%'");
				sql.append(" AND v1.INTEREST_DT = ").append(createDateTimeEnds);			
			}else{
				sql.append(" v1.INTEREST_DT = ").append(createDateTimeBegins);
			}
			sql.append(" ORDER BY ENTERPRISE_NAME,INTEREST_DT  DESC LIMIT " + (page.getPageIndex() - 1) * page.getPageSize() + " , " + page.getPageSize());
		}
//		sql.append(" limit "+ (page.getPageIndex() - 1) * page.getPageSize() + "," + page.getPageSize()*page.getPageIndex());
		System.out.println(sql.toString());
		Session session = SessionRepository.getCurrentSession();
		List<Integer> counts = session.createSQLQuery(countSql.toString()).addScalar("c").list();
		int totalRecordCount = 0;
		for (Object l : counts) {
			Object os = (Object)l;
			totalRecordCount = ((BigInteger) os).intValue();
		}
		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("ENTERPRISE_ID").addScalar("FINANCE_ID").addScalar("ENTERPRISE_NAME").addScalar("FINANCE_AMOUNT").addScalar("BULKSTOCK_VALUATION").addScalar("INTEREST"). addScalar("INTEREST_DT").list();
		PageList<DaysEarningEnterpriseBaseDetail> daysEarningEnterpriseBaseDetail = new PageList<>(page, totalRecordCount);
//		datas = session.createSQLQuery(sql1.toString()).addScalar("ENTERPRISE_ID").addScalar("ENTERPRISE_NAME").addScalar("FINANCE_AMOUNT").addScalar("BULKSTOCK_VALUATION").addScalar("INTEREST"). addScalar("INTEREST_DT").list();
		for (Object l : datas) {
			DaysEarningEnterpriseBaseDetail d = new DaysEarningEnterpriseBaseDetail();
			Object[] os = (Object[])l;
			d.setEnterpriseId(((BigInteger) os[0]).longValue());
			d.setFinanceId(((BigInteger) os[1]).longValue());
			d.setEnterpriseName((String) os[2]);
			d.setFinanceAmount((BigDecimal) os[3]);
			d.setBulkstockValuation((BigDecimal) os[4]);
			d.setInterest((BigDecimal) os[5]);
			
//			d.setInterestDt((DateUtils.fromDateInt(((BigInteger)os[4]).intValue())).toString());
			if(((BigInteger)os[6]).intValue() >0){
				String interestDtss= String.valueOf(((BigInteger)os[6]).intValue());
				String str=interestDtss.substring(0, 4);
				String str2=interestDtss.substring(4, 6);
				String str3=interestDtss.substring(6, 8);
				d.setInterestDt(str+"-"+str2+"-"+str3);
			}
			daysEarningEnterpriseBaseDetail.add(d);
		}
		
		SessionRepository.closeCurrentSession();
		return daysEarningEnterpriseBaseDetail;
	}
	
	@Override
	public EarningSummaryBaseDetail inquireEarningSummarys() {
		EarningSummaryEntity entity = earningSummaryService.inquireEarningSummarys();
		if (entity != null) {
			return EnterpriseCastor.toEarningSummaryBaseDetail(entity);
		}
		return new EarningSummaryBaseDetail();
	}

	@Override
	public PageList<DaysEarningBaseDetail> inquireMonthDaysEarningPageList(
			String financeNumber, Date earningDateStart, Date earningDateEnd, PageCriteria page) {
		PageList<DaysEarningEntity> daysEarningList = daysEarningService.inquireMonthDaysEarningPageList(financeNumber, earningDateStart, earningDateEnd, page);
		PageList<DaysEarningBaseDetail> daysEarningBaseDetailList = new PageList<>(page, daysEarningList.getTotalRecordCount());
		for (DaysEarningEntity entity : daysEarningList) {
			daysEarningBaseDetailList.add(EnterpriseCastor.toDaysEarningBaseDetail(entity));
		}
		return daysEarningBaseDetailList;
	}
}
